use std::sync::{atomic::{AtomicBool, Ordering}, Arc};
use serde_json::json;
use webrtc::data_channel::RTCDataChannel;
use serde::{Deserialize, Serialize};
use once_cell::sync::Lazy;

// 用以标志是否成功握手
pub static IS_ACK: Lazy<Arc<AtomicBool>> = Lazy::new(|| Arc::new(AtomicBool::new(false)));
#[derive(Serialize, Deserialize, Debug)]
struct Ack {
    r#type: String,
}

pub async fn message_channel_init(message_channel: Arc<RTCDataChannel>) {
    let channel = message_channel.clone();
    // 通道打开时握手
    message_channel.on_open(Box::new(move || {
        Box::pin(async move {
            hand_shake(channel).await;
        })
    }));

    let channel = message_channel.clone();
    // 接收消息
    message_channel.on_message(Box::new(move |message| {
        let message = String::from_utf8_lossy(&message.data).to_string();
        let channel = channel.clone();
        Box::pin(async move{
            solve_message(message, channel).await; // 处理消息
        })
    }));
    println!("message通道初始化结束");
}

fn generate_message(content: &str, target: &str) -> String {
    let messsage = format!(
        r#"{{
            "type": "Message",
            "content": "{}", // JSON字符串
            "id": "41f93d5a-900f-4d33-b7a1-2d4ca6747072",
            "target": "{}",
            "cv": ""
    }}"#, content, target
    );
    return messsage;
}
async fn hand_shake(message_channel: Arc<RTCDataChannel>) {
    let hand_shake = json!(
        {
            "type": "Handshake",
            "version": "messageV1",
            "id": "f9c5f412-0e69-4ede-8e62-92c7f5358c56",
            "cv": "",
        }
    );
    message_channel.send_text(hand_shake.to_string()).await.unwrap();
}

async fn solve_message(message: String, message_channel: Arc<RTCDataChannel>) {
    if let Ok(response) = serde_json::from_str::<Ack>(&message) {
            if(response.r#type == "HandshakeAck") {
                // 握手成功, 发送配置信息
                println!("message通道握手成功");
                IS_ACK.store(true, Ordering::SeqCst);
                // UI配置
                message_channel.send_text(configuration()).await.unwrap();
                // 客户端ID
                message_channel.send_text(client_id()).await.unwrap();
                // 设备方向
                message_channel.send_text(orientation()).await.unwrap();
                // 触摸输入
                message_channel.send_text(touch_input()).await.unwrap();
                // 设备能力
                message_channel.send_text(device_capability()).await.unwrap();
                // 屏幕尺寸
                message_channel.send_text(screen_size()).await.unwrap();

                println!("message通道配置发送完成");
            }
    }
}

fn configuration() -> String {
    let content = json!(
        {
        "version": [0, 2, 0],
        "systemUis": [10, 19, 31, 27, 32, -41]
        }
    ).to_string();
    let target = "/streaming/systemUi/configuration";
    return generate_message(&content, target);
}
fn client_id() -> String {
    let content = json!(
        { "clientAppInstallId": "c11ddb2e-c7e3-4f02-a62b-fd5448e0b851" }
    ).to_string();
    let target = "/streaming/properties/clientappinstallidchanged";
    return generate_message(&content, target);
}
fn orientation() -> String {
    let content = json!(
        { "orientation": 0 }
    ).to_string();
    let target = "/streaming/characteristics/orientationchanged";
    return generate_message(&content, target);
}
fn touch_input() -> String {
    let content = json!(
        { "touchInputEnabled": false }
    ).to_string();
    let target = "/streaming/characteristics/touchinputenabledchanged";
    return generate_message(&content, target);
}
fn device_capability() -> String {
    let content = json!(
        {}
    ).to_string();
    let target = "/streaming/characteristics/clientdevicecapabilities";
    return generate_message(&content, target);
}
fn screen_size() -> String {
    let content = json!(
        {
            "horizontal": 1920,
            "vertical": 1080,
            "preferredWidth": 1920,
            "preferredHeight": 1080,
            "safeAreaLeft": 0,
            "safeAreaTop": 0,
            "safeAreaRight": 1920,
            "safeAreaBottom": 1080,
            "supportsCustomResolution": true
        }
    ).to_string();
    let target = "/streaming/characteristics/dimensionschanged";
    return generate_message(&content, target);
}